//
//  LGTencentCloudTool.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/6/5.
//

#import "LGLoginManager.h"
#import "LGNavigationController.h"
#import "LGLoginViewController.h"
#import <ImSDK_Plus/ImSDK_Plus.h>
#import "TUILogin.h"

@implementation LGLoginManager

//登录腾讯云
+(void)loginTencentCloud{
    if(!XGUserId || !XGUserSign){
        [RequestUtil withPOST:@"/doctor/user/imLogin" parameters:@{} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
            if(code == 200){
                [[NSUserDefaults standardUserDefaults] setValue:LGNSString(returnData[@"user_id"]) forKey:@"XGUserId"];
                [[NSUserDefaults standardUserDefaults] setValue:LGNSString(returnData[@"sign"]) forKey:@"usersign"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                [TUILogin login:TUIAppId userID:LGNSString(returnData[@"user_id"]) userSig:returnData[@"sign"] succ:^{
                    NSLog(@">>腾讯云登录成功>>>%@--%@",XGUserId,XGUserSign);
                    [LGLoginManager registDeviceToken];
                } fail:^(int code, NSString *msg) {
                    NSLog(@">>腾讯云登录失败>>>%@",msg);
                }];
            }else{
                [TooltipView showMessage:message offset:0];
            }
        } error:^(NSError *error) {
            [TooltipView showMessage:LGErrorMessage offset:0];
        }];
    }else{
        [TUILogin login:TUIAppId userID:XGUserId userSig:XGUserSign succ:^{
            NSLog(@">>腾讯云登录成功>>>%@--%@",XGUserId,XGUserSign);
            [LGLoginManager registDeviceToken];
            
        } fail:^(int code, NSString *msg) {
            NSLog(@">>腾讯云登录失败>>>%@",msg);
        }];
    }
}
//注册deviceToken == 移动推送用
+(void)registDeviceToken{
    NSData *deviceToken = [[NSUserDefaults standardUserDefaults] valueForKey:@"deviceToken"];
    if (deviceToken) {
        V2TIMAPNSConfig *confg = [[V2TIMAPNSConfig alloc] init];
        confg.businessID = certificateID;
        confg.token = deviceToken;
        [[V2TIMManager sharedInstance] setAPNS:confg succ:^{
            NSLog(@"注册APNS成功--%d", confg.businessID);
        } fail:^(int code, NSString *msg) {
             NSLog(@"注册APNS失败--%d--%@", code, msg);
        }];
    }
}

//退出登录
+(void)logoutAction{
    [[NSUserDefaults standardUserDefaults] setValue:@"N" forKey:@"islogin"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"userid"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"phone"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"XGUserId"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"usersign"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [TUILogin logout:nil fail:nil];
    LGNavigationController *navController = [[LGNavigationController alloc]initWithRootViewController:[[LGLoginViewController alloc] init]];
    [UIApplication sharedApplication].keyWindow.rootViewController = navController;
}

@end
